package com.ai.wx.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ai.core.constant.GlobalConstant;
import com.ai.core.dao.BaseDaoI;
import com.ai.core.pagemode.Grid;
import com.ai.core.pagemode.Json;
import com.ai.core.pagemode.PageFilter;
import com.ai.wx.entity.AgentBrokerage;
import com.ai.wx.entity.AgentBrokerageDraw;
import com.ai.wx.entity.AgentBrokerageDtl;
import com.ai.wx.entity.AgentPromotion;
import com.ai.wx.entity.AgentUser;
import com.ai.wx.entity.PromotionCodeRes;
import com.ai.wx.exception.FlowMarketException;
import com.ai.wx.service.AgentService;
import com.ai.wx.service.SystemService;
import com.ai.wx.util.WeixinUtil;

@Service
public class AgentServiceImpl implements AgentService {
	@Autowired
	private BaseDaoI<AgentUser> agentUserDao; 
	@Autowired
	private BaseDaoI<PromotionCodeRes> promCodeResDao;
	@Autowired
	private BaseDaoI<AgentPromotion> agentPromotionDao;
	@Autowired
	private BaseDaoI<AgentBrokerage> agentBrokerageDao;
	@Autowired
	private BaseDaoI<AgentBrokerageDtl> agentBrokerageDtlDao;
	@Autowired
	private SystemService systemService;
	
	@Autowired
	private BaseDaoI<AgentBrokerageDraw> agentBrokerageDrawDao;

	public Json agentLogin(String agentUser, String password) {
		Json j = new Json();
		String hql = "from AgentUser where agentUser =:agentUser";
		AgentUser user = agentUserDao.get(hql);
		if (user == null) {
			j.setMsg("该用户不存在");
			return j;
		}
		if (StringUtils.equals(password, user.getPassword())) {
			if (user.getState() == 1) {
				j.setSuccess(true);
				j.setObj(user);
				j.setMsg("登陆成功");
				return j;
			} else {
				j.setMsg("该用户已经被锁定");
				return j;
			}
		} else {
			j.setMsg("密码错误");
			return j;
		}

	}

	public boolean isExistAgentUser(String agentUser) {
		String hql = "select count(*) from AgentUser where agentUser = :agentUser";
		HashMap params = new HashMap();
		params.put("agentUser", agentUser);
		Long count = agentUserDao.count( hql, params);
		if (count > 0) {
			return false;
		} else {
			return true;
		}
	}

	public Json registerAgentUser(AgentUser agentUser) {
		Json j = new Json();
		try{ 
			if(StringUtils.isNotEmpty(agentUser.getIdCardPicF())){
				String accessToken = systemService.getAccessToken();
				String idCardPicFName = WeixinUtil.downloadPicture(accessToken, agentUser.getIdCardPicF(), 5);
				agentUser.setIdCardPicF(idCardPicFName);
			}
			if(StringUtils.isNotEmpty(agentUser.getIdCardPicF())){
				String accessToken = systemService.getAccessToken();
				String idCardPicBName = WeixinUtil.downloadPicture(accessToken, agentUser.getIdCardPicB(), 5);
				agentUser.setIdCardPicB(idCardPicBName);
			}
			
			agentUser.setAgentState(GlobalConstant.AGENT_STATE_APPROVING);
			agentUserDao.save(agentUser); 
			AgentBrokerage brokerage = new AgentBrokerage();
			brokerage.setAgentId(agentUser.getId());
			brokerage.setCharge(0);
			brokerage.setLockCharge(0);
			brokerage.setTotalCharge(0);
			brokerage.setTotalDram(0);
			brokerage.setYesterdayCharge(0);
			agentBrokerageDao.save(brokerage);
			
			j.setSuccess(true);
			j.setObj(agentUser);
		 
		}catch(Exception e){
			e.printStackTrace();
			j.setMsg(e.getMessage());
		}
		return j;
	}

	public PromotionCodeRes preOccupyPromCode(int ownAgentId) {
		String hql = "from PromotionCodeRes where resState = 1";
		List<PromotionCodeRes> promCodeResList = promCodeResDao.find(hql, null, 1, 1);
		if (promCodeResList != null && promCodeResList.size() == 1) {
			PromotionCodeRes promotionCodeRes = promCodeResList.get(0);
			promotionCodeRes.setResState(GlobalConstant.RES_PRE_OCCUPY);
			promotionCodeRes.setOwnAgentId(ownAgentId);
			promotionCodeRes.setOwnDate(new Date());
			promCodeResDao.update(promotionCodeRes);
			return promotionCodeRes;
		} else {
			return null;
		}
	}

	public PromotionCodeRes getPromCodeRes(String promotionCode) {

		String hql = "from PromotionCodeRes where promotionCode =:promotionCode";

		HashMap params = new HashMap();
		params.put("promotionCode", promotionCode);
		List<PromotionCodeRes> promCodeResList = promCodeResDao.find(hql, params);
		if (promCodeResList != null && promCodeResList.size() == 1) {
			return promCodeResList.get(0);
		} else {
			return null;
		}
	}

	public void occupyPromCode(AgentPromotion agentPromoiton) throws FlowMarketException {
		String promotionCode = agentPromoiton.getPromotionCode();
		PromotionCodeRes promotionCodeRes = getPromCodeRes(promotionCode);
		if (promotionCodeRes != null) {
			if (promotionCodeRes.getOwnAgentId().intValue() == agentPromoiton.getAgentId().intValue()) {
				promotionCodeRes.setResState(GlobalConstant.RES_OCCUPIED);
				promCodeResDao.update(promotionCodeRes);
			} else {
				throw new FlowMarketException("错误：优惠码失效，请重新选择优惠码");
			}
		} else {
			throw new FlowMarketException("错误：优惠码【" + promotionCode + "】系统中未找到");
		}
		agentPromotionDao.save(agentPromoiton);
	}
	
	
	public AgentPromotion buyAgentPromoiton(Integer agentId){
		String hql = "from AgentPromotion where agentId =:agentId and state = 1";
		HashMap param = new HashMap();
		param.put("agentId", agentId);
		AgentPromotion agentPromoiton= agentPromotionDao.get(hql,param);
		if(agentPromoiton == null){
			PromotionCodeRes codeRes = preOccupyPromCode(agentId);
			agentPromoiton = new AgentPromotion();
			agentPromoiton.setAgentId(agentId);
			agentPromoiton.setPromotionCode(codeRes.getPromotionCode());
			agentPromotionDao.save(agentPromoiton);
		}
		return agentPromoiton;
	}
	
	

	public Json applyDrawBrokerage(AgentBrokerageDraw draw) throws FlowMarketException {
		Json j = new Json();
		AgentBrokerage agentBrokerage = getAgentBrokerage(draw.getAgentId());
		if (agentBrokerage != null) {
			if (agentBrokerage.getLockCharge() > 0) {
				j.setMsg("您当前已经申请了佣金提取，提取完毕后才能再次发起申请");

				return j;
			}
			if (agentBrokerage.getCharge() > draw.getDrawCharge()) {
				agentBrokerage.setLockCharge(draw.getDrawCharge());
				agentBrokerageDao.save(agentBrokerage);
				draw.setDrawDate(new Date());
				draw.setDrawState(GlobalConstant.DRAW_STATE_APPROVING);
				agentBrokerageDrawDao.save(draw);
				j.setSuccess(true);

				 
			} else {
				j.setMsg("您的佣金余额小于申请的额度");
 
			}

		}else{ 
			j.setMsg("您还没有佣金"); 
		}
		return j;
	}

	public AgentBrokerage getAgentBrokerage(Integer agentId) {
		String hql = " from AgentBrokerage where agentId = :agentId and state = 1";
		HashMap params = new HashMap();
		params.put("agentId", agentId);
		AgentBrokerage agentBrokerage = agentBrokerageDao.get(hql, params);
		return agentBrokerage;
	}

	public Long getBrokerageCount(Integer agentId) {
		String hql = "select count(*) from AgentBrokerageDtl where agentId = :agentId and state = 1";
		HashMap params = new HashMap();
		params.put("agentId", agentId);
		Long count = agentBrokerageDtlDao.count(hql, params);
		return count;
	}
	
	public Grid getAgentBrokerageDtl(Integer agentId, PageFilter page) {
		Grid g = new Grid();
		String hql = " from AgentBrokerageDtl where agentId = :agentId and state = 1 order by id desc";
		String countHql = "select count(*) from AgentBrokerageDtl where agentId = :agentId and state = 1";

		HashMap params = new HashMap();
		params.put("agentId", agentId);
		List<AgentBrokerageDtl> list = agentBrokerageDtlDao.find(hql, params, page.getPage(), page.getRows());
		//Long count = agentBrokerageDtlDao.count(countHql, params);
		g.setRows(list);
		//g.setTotal(count);
		return g;
	}

	
 

	public Grid getAgentBrokerageDraw(Integer agentId, Integer drawState, Date startDate, Date endDate, PageFilter page) {
		Grid g = new Grid();
		HashMap params = new HashMap();
		params.put("agentId", agentId);

		String hql = " from AgentBrokerageDraw where agentId = :agentId and state = 1";
		if (drawState != null && drawState > 0) {
			hql += " and drawState = :drawState ";
			params.put("drawState", drawState);
		}
		if (startDate != null) {
			hql += " and drawDate >= :startDate ";
			params.put("startDate", startDate);
		}
		if (endDate != null) {
			hql += " and drawDate >= :endDate ";
			params.put("endDate", endDate);
		}
		String countHql = "select count(*) " + hql;
		hql += "  order by id desc";
		List<AgentBrokerageDraw> list = agentBrokerageDrawDao.find(hql, params, page.getPage(), page.getRows());
		//Long total = agentBrokerageDrawDao.count(countHql, params);
		g.setRows(list);
		//g.setTotal(total);
		return g;
	}

	@Override
    public boolean isAgentUser(String openId) {
		String hql = "select count(*) from AgentUser where openid = :openid";
		HashMap params = new HashMap();
		params.put("openid", openId);
		Long count = agentUserDao.count( hql, params);
		if (count > 0) {
			return false;
		} else {
			return true;
		} 
    }
	
	
	@Override
    public AgentUser getAgentUserByOpenId(String openId) {
		String hql = "from AgentUser where openid = :openid";
		HashMap params = new HashMap();
		params.put("openid", openId);
		AgentUser user = agentUserDao.get( hql, params);
		return user;
    }

	@Override
    public void setAgentPromoiton(Integer agentId, Integer promotionRate) throws FlowMarketException {
		AgentPromotion promotion =   buyAgentPromoiton(agentId);
		if(promotion.getPromotionRate()!=null){
			throw new FlowMarketException("您的优惠码已经设置成功，无法再次设置");
		}
		promotion.setPromotionRate(promotionRate);
		agentPromotionDao.save(promotion);
    }
}
